<template>
  <div class="flex buttons">
    <el-button type="success" :icon="RefreshRight" size="small" />
    <el-button type="danger" :icon="Delete" size="small" @click="handleDelete"
      >删除</el-button
    >
    <el-button type="primary" :icon="Edit" size="small" @click="visible = true"
      >撰写</el-button
    >
  </div>
  <div class="mail">
    <!-- 头部 -->
    <div class="head">
      <!-- 搜索框 -->
      <div class="mt-4">
        <el-input
          v-model="input3"
          placeholder="请输入"
          class="input-with-select"
          size="small"
          clearable
        >
          <template #prepend>
            <el-select
              v-model="select"
              placeholder="发件人"
              style="width: 115px"
            >
              <el-option label="发件人" value="1" />
              <el-option label="收件人" value="2" />
              <el-option label="邮件主题" value="3" />
              <el-option label="邮件内容" value="4" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
      </div>
      <!-- 按钮组 -->
    </div>
    <!-- 撰写邮件弹出框 -->
    <el-dialog
      v-model="visible"
      :show-close="true"
      top="2vh"
      :before-close="handleClose"
    >
      <template #header="{ titleId, titleClass }">
        <div class="my-header">
          <h4 :id="titleId" :class="titleClass">撰写邮件</h4>
        </div>
      </template>
      <!-- 弹出框表单 -->
      <el-form :model="form" label-width="120px">
        <el-form-item label="邮件主题" required prop="theme">
          <el-input v-model="form.theme" />
        </el-form-item>
        <el-form-item label="级别" required>
          <el-radio-group v-model="form.leval">
            <el-radio label="普通" />
            <el-radio label="首要" />
            <el-radio label="紧急" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="收件人" required>
          <el-input v-model="form.recipient" />
        </el-form-item>
        <!-- 富文本编辑器 -->
        <el-form-item label="邮件内容" required>
          <TextEditor v-model="form.msg"></TextEditor>
        </el-form-item>
        <el-form-item label="发送时间">
          <el-input readonly="true" v-model="currentTime" />
        </el-form-item>
        <!-- 文件上传 -->
        <el-form-item label="附件上传">
          <el-upload
            ref="upload"
            class="upload-demo"
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :limit="1"
            :on-exceed="handleExceed"
            :auto-upload="false"
          >
            <template #trigger>
              <el-button type="primary" size="small">选择文件</el-button>
            </template>
            <el-button
              class="ml-3"
              type="success"
              @click="submitUpload"
              size="small"
            >
              上传
            </el-button>
            <template #tip>
              <div class="el-upload__tip text-red">
                limit 1 file, new file will cover the old file
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item class="form-footer">
          <el-button type="primary" @click="submitAndExit">发送邮件</el-button>
          <el-button type="success">保存草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 邮件表格 -->
    <div class="mail">
      <el-tabs
        :tab-position="tabPosition"
        style="height: 100%"
        class="demo-tabs"
      >
        <el-tab-pane label="收件箱">
          <el-table
            ref="multipleTableRef"
            :data="registerInfo"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" ref="checked" />
            <el-table-column
              property="theme"
              label="邮件主题"
              show-overflow-tooltip
            />
            <el-table-column
              property="recipient"
              label="收件人"
              show-overflow-tooltip
            />
            <el-table-column
              property="leval"
              label="级别"
              show-overflow-tooltip
            />
            <el-table-column
              property="sendTime"
              label="发送时间"
              show-overflow-tooltip
            />
            <el-table-column label="操作" width="200px" align="center">
              <template #default="scope">
                <el-button type="danger" @click="handleRemove(scope.row)"
                  >删除</el-button
                >
                <el-button
                  type="primary"
                  @click="handleclick(scope.row)"
                  :dialogTableVisible="dialogTableVisible"
                  style="margin-right: 12px"
                  >查看</el-button
                >
                <!-- 分页 -->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="发件箱"></el-tab-pane>
        <el-tab-pane label="草稿箱"></el-tab-pane>
        <el-tab-pane label="废件箱"></el-tab-pane>
      </el-tabs>
    </div>
    <!-- 查看详情 -->
    <el-dialog v-model="dialogTableVisible" title="邮件查看" width="90%">
      <el-table :data="gridData">
        <el-table-column property="theme" label="邮件主题" />
        <el-table-column property="recipient" label="收件人" />
        <el-table-column property="leval" label="级别" />
        <el-table-column property="annex" label="附件" />
        <el-table-column property="sendTime" label="发送人" />
        <el-table-column property="msg" label="内容" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 引入搜索框组件
import { Search } from '@element-plus/icons-vue'
const input3 = ref('')
const select = ref('')
// 引入按钮组件
import { Delete, Edit, RefreshRight } from '@element-plus/icons-vue'

import { ref, watch, onMounted } from 'vue'

// 引入标签页位置
const tabPosition = ref('left')
// 引入表格组件
import { ElTable } from 'element-plus'
//引入邮件编辑弹出框
import { ElButton, ElDialog } from 'element-plus'
// 引入富文本编辑器
import TextEditor from '@/components/textEditor.vue'

// 当前时间
const currentTime = ref('')
onMounted(() => {
  const date = new Date()
  currentTime.value = date.toLocaleDateString()
})

// 引入文件上传
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

// 引入api方法
import {
  getMailInfo,
  addMailInfo,
  deleteMailInfo,
  // setMailInfo,
} from '@/api/getapi'
const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

const submitUpload = () => {
  upload.value!.submit()
}

// const msg = ref('')
//引入弹出框表单
// do not use same name with ref
const form = ref<any>({
  theme: '',
  leval: '',
  recipient: '',
  date: '',
  sendTime: '2023/10/11',
  msg: '',
  // date2: '',
  // delivery: false,
  // type: [],
  // resource: '',
  // desc: '',
})
import { ElMessageBox, ElMessage } from 'element-plus'
const dialogFormVisible = ref(false)
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确认关闭吗？关闭后无法保存信息！')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

// 新增提交
const submitAndExit = async () => {
  try {
    const forData = form.value
    console.log('fordata', forData)
    const result = await addMailInfo(forData)
    console.log('添加', result)
    form.value = {}
    dialogFormVisible.value = false
    ElMessage({
      message: '添加成功',
      type: 'success',
      duration: 1500,
    })
  } catch (error) {
    ElMessage({
      message: '材料编码重复，添加失败！',
      type: 'error',
      duration: 1500,
    })
  }
  getData()
}

// 删除
const handleDelete = async (prod: any) => {
  try {
    const result = await deleteMailInfo(prod)
    console.log(result)
    ElMessage({
      message: '删除成功',
      type: 'success',
      duration: 1500,
    })
  } catch (error) {
    console.log(error)
  }
  getData()
}

// 表格渲染
const registerInfo = ref<MailInfo[]>([])
const tableData = ref<any>()
const getData = async () => {
  const result = await getMailInfo()
  tableData.value = result
  total.value = tableData.value.length
  show()
}
getData()

// 分页器
const total = ref()
//分页器数据
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const show = () => {
  registerInfo.value = tableData.value.slice(
    pageSize4.value * (currentPage4.value - 1),
    pageSize4.value * currentPage4.value,
  )
}
watch([currentPage4, pageSize4], (val) => {
  console.log('val', val)
  show()
})

// 删除表格数据
const handleRemove = async (prod: any) => {
  try {
    const result = await deleteMailInfo(prod)
    console.log(result)
    registerInfo.value = result
    ElMessage({
      message: '删除成功',
      type: 'success',
      duration: 1500,
    })
  } catch (error) {
    console.log(error)
  }
  getData()
}

// 表格查看
const gridData = ref<any>()
const dialogTableVisible = ref(false)
const handleclick = (result: any) => {
  dialogTableVisible.value = true
  const arr = []
  arr.push(result)
  gridData.value = arr
}

const visible = ref(false)
// interface Mail {
//   theme: string
//   recipient: string
//   leval: string
//   annex: string
//   sender: string
//   date1: string
//   date2: string
// }

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<MailInfo[]>([])
const handleSelectionChange = (val: MailInfo[]) => {
  multipleSelection.value = val
}

// const tableData: Mail[] = []
//   {
//     theme: '该发工资了谢谢',
//     recipient: 'admin',
//     leval: '紧急',
//     annex: '',
//     sender: '德尔普',
//     date: '2023-09-12',
//   },
//   {
//     theme: '该发工资了谢谢',
//     recipient: 'admin',
//     leval: '紧急',
//     annex: '',
//     sender: '德尔普',
//     date: '2023-09-12',
//   },
//   {
//     theme: '该发工资了谢谢',
//     recipient: 'admin',
//     leval: '紧急',
//     annex: '',
//     sender: '德尔普',
//     date: '2023-09-12',
//   },
//   {
//     theme: '该发工资了谢谢',
//     recipient: 'admin',
//     leval: '紧急',
//     annex: '',
//     sender: '德尔普',
//     date: '2023-09-12',
//   },
// ]
</script>

<style lang="scss" scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.el-tabs--right .el-tabs__content,
.el-tabs--left .el-tabs__content {
  height: 100%;
}

.head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.head .input-with-select {
  width: 500px;
  margin-left: 82px;
}

// 弹出框头部样式
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.buttons {
  float: right;
  width: 300px;
  height: 40px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.mail {
  float: left;
  width: 100%;
}
</style>
